<template>
  <div class="main-container" v-loading="loading" element-loading-text="努力加载中...">
    <div class="content-container">
      <div class="title-container">
        <div class="title-text">肺功能</div>
      </div>

      <div class="blood-oxygen-container" :class="oxygenLevelClass">
        <div class="oxygen-display">
          <el-text class="oxygen-value">{{ formattedOxygen }}</el-text>
          <el-text class="oxygen-label">血氧浓度</el-text>
        </div>
        <div class="oxygen-status">
          <el-text class="status-text">本次测量{{ oxygenStatus }}</el-text>
        </div>

        <!-- 添加过渡线条 -->
        <div class="divider"></div>

        <div class="reference-range">
          <div class="range-title">
            <el-text class="title-text">血氧浓度参考范围</el-text>
          </div>
          <div class="range-bar">
            <div class="range-segment normal-segment">
              <el-text class="segment-text">正常<br/>≥95%</el-text>
            </div>
            <div class="range-segment low-segment">
              <el-text class="segment-text">偏低<br/>90%-94%</el-text>
            </div>
            <div class="range-segment very-low-segment">
              <el-text class="segment-text">过低<br/>＜90%</el-text>
            </div>
          </div>
        </div>
      </div>


      <div class="chart-container">
        <div ref="chartRef" style="width: 100%; height: 100%"></div>
      </div>

      <div class="copd-container">

        <!-- 当前数据分析和诊断评估 -->
        <div class="analysis-container">
          <!-- 当前数据分析 -->
          <div class="info-item">
            <el-text class="info-label">FEV1（第一秒用力呼气量）</el-text>
            <el-text class="info-value">{{ fev1.toFixed(2) }}L</el-text>
          </div>
          <div class="info-item">
            <el-text class="info-label">FVC（用力肺活量）</el-text>
            <el-text class="info-value">{{ fvc.toFixed(2) }}L</el-text>
          </div>
          <div class="info-item">
            <el-text class="info-label">FEV1/FVC比值</el-text>
            <el-text class="info-value comparison">
<!--              {{ fev1FvcRatio }} {{ comparisonOperator }}-->
              <el-text :class="['threshold', { large: isAbnormal, small: !isAbnormal }]">82.3%</el-text>
            </el-text>
          </div>
          <div class="info-item">
            <el-text class="info-label">诊断结果</el-text>
            <el-text class="info-value diagnosis green-text" >
              正常
            </el-text>
<!--            <el-text class="info-value diagnosis" :class="{ abnormal: isAbnormal, normal: !isAbnormal }">-->
<!--              {{ isAbnormal ? "肺功能（异常）" : "正常" }}-->
<!--            </el-text>-->
          </div>


        </div>

      </div>



    </div>
  </div>
</template>

<script setup>
import '@/assets/css/reportCard.css';
import '@/components/copd/copd_info.css';
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import * as echarts from 'echarts';
import {markRaw, onMounted, onUnmounted, ref, watch, computed} from "vue";
import sleepData from "@/api/sleepData.js";
import {ElMessage} from "element-plus";
onMounted(() => {

  //获取慢阻肺数据
  getCOPDData(props.currentReportId);

  // getHeartData(props.currentReportId);
  // getOxygenDate(props.currentReportId);

  // 图表初始化
  if (useMockData.value) {
    generateMockData()
  }
  calculateMetricsAndChartData()
  initChart()

  // 监听窗口大小变化
  // window.addEventListener('resize', resizeCharts);

});
onUnmounted(()=>{
  if (currentUserHeartRateData.value.evaluation === evaluationBackup.value){
  }else {
    const updateHeartRateDto = {
      reportId: props.currentReportId,
      evaluation: currentUserHeartRateData.value.evaluation
    }
    sleepData.updateHeartEvaluate(updateHeartRateDto).then((res)=>{
      if (res.data.code === 200){
      }
    }).catch((err)=>{
      console.log(err)
    })
  }

  // 图表清理
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
  // window.removeEventListener('resize', resizeCharts)
  disposeChart()
});
const props = defineProps({
  currentReportId: Number,
  enableEdit:Boolean
});
watch(() => props.currentReportId, (newId) => {
  //获取慢阻肺数据
  getCOPDData(newId);

  // 重新初始化图表
  calculateMetricsAndChartData()
  initChart()
  // getOxygenDate(newId);
  // getHeartData(newId);
});
watch(() => props.enableEdit, (newValue) => {
  enableEdit.value = newValue
});
const enableEdit = ref(props.enableEdit)
const loading = ref(false)
const evaluationBackup = ref('')

const saveHeartData = (data) => {
  const cache = {
    data,
    timestamp: new Date().getTime(), // 当前时间戳
  };
  localStorage.setItem('heartData', JSON.stringify(cache));
};

const bloodOxygen = ref(0)

//获取慢阻肺的数据
const getCOPDData = (copdReportId) => {
  loading.value = false;
  sleepData.getCOPDData(copdReportId).then((res) => {
    if (res.data.code === 200 && res.data.data){
      const copdData = res.data.data;
      console.log('111',copdData)
      bloodOxygen.value = copdData.bloodOxygen;
      console.log('血氧数据：',bloodOxygen.value)

    }
  })

}

// 格式化血氧值显示（如 0.95 → "95%"）
const formattedOxygen = computed(() => {
  return `${(bloodOxygen.value * 100).toFixed(0)}%`
});

// 血氧状态文字描述
const oxygenStatus = computed(() => {
  const oxygenPercentage = bloodOxygen.value * 100;
  if (oxygenPercentage >= 95) {
    return "血氧水平正常";
  } else if (oxygenPercentage >= 90) {
    return "血氧水平偏低";
  } else {
    return "血氧水平过低，请注意！";
  }
});

// 根据血氧值返回对应的 CSS class
const oxygenLevelClass = computed(() => {
  const oxygenPercentage = bloodOxygen.value * 100;
  if (oxygenPercentage >= 95) {
    return "normal";
  } else if (oxygenPercentage >= 90) {
    return "low";
  } else {
    return "very-low";
  }
});

//
const chartRef = ref(null)
const chartInstance = ref(null)
const fev1 = ref(0)
const fvc = ref(0)
const chartData = ref([])
const totalTime = ref(0)
const maxFlowRate = ref(0)
const useMockData = ref(true)
const mockSamplingData = ref([])
const mockFrequency = ref(200)

// 计算属性
const fev1FvcRatio = computed(() => {
  const ratio = ((fev1.value / fvc.value) * 100).toFixed(1)
  return `${ratio}%`
})

const isAbnormal = computed(() => {
  return fev1.value / fvc.value < 0.7
})

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  // 销毁旧实例
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }

  chartInstance.value = echarts.init(chartRef.value)

  const option = {
    backgroundColor: '#ffffff',
    xAxis: {
      type: "value",
      name: "t/s",
      nameTextStyle: {
        fontSize: 14,
        fontWeight: 'bold',
        color: "#333",
        padding: [10, 0, 0, 0]
      },
      min: 0,
      max: totalTime.value,
      axisTick: { show: false },
      axisLabel: { show: false },
      scale: false,
      axisLine: {
        lineStyle: { color: "#999" }
      },
      splitLine: { show: false }
    },
    yAxis: {
      type: "value",
      name: "Flow (L/s)",
      nameLocation: "middle",  // 推荐用 middle 或 center，避免被顶部遮挡
      nameTextStyle: {
        fontSize: 14,
        fontWeight: 'bold',
        color: "#333",
        padding: [0, 0, 10, 0]
      },
      axisLabel: { show: false },  // 隐藏刻度数字
      axisTick: { show: false },   // 可选：隐藏刻度线
      axisLine: {
        lineStyle: { color: "#999" }
      },
      splitLine: { show: false },  // 可选：隐藏网格线
      min: 0,
      max: Math.ceil(maxFlowRate.value / 5) * 5
    },
    series: [
      {
        name: "呼气流速",
        type: "line",
        smooth: true,
        data: chartData.value,
        showSymbol: false,
        lineStyle: {
          color: "#5B9BD5",
          width: 2
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "#DAEAF6" },
              { offset: 1, color: "#EEF4FA" }
            ]
          }
        },
        silent: true,
        hoverAnimation: false
      },
      {
        name: "前两秒呼气流速",
        type: "line",
        data: chartData.value.filter(point => point[0] <= 1.5),
        showSymbol: false,
        lineStyle: { width: 0, color: "#FF7E50" },
        areaStyle: { color: "rgba(255, 126, 80, 0.45)" },
        stack: '总量',
        silent: true,
        hoverAnimation: false
      }
    ],
    tooltip: { trigger: 'none' },
    grid: {
      left: '8%',
      right: '3%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    }
  }

  chartInstance.value.setOption(option)
}

// 生成模拟数据
const generateMockData = () => {
  const duration = 4
  const totalPoints = duration * mockFrequency.value

  mockSamplingData.value = []
  const generateAbnormalData = Math.random() > 0.5

  const peakTime = 1.2 + Math.random() * 0.6
  const peakValue = 12 + Math.random() * 6
  const riseSlope = 1.5 + Math.random() * 0.6
  const postPeakDecayFactor = 0.5 + Math.random() * 0.3
  const laterDecayFactor = 1.3 + Math.random() * 0.4
  const transitionTime = 2.3 + Math.random() * 0.4

  let fev1ScaleFactor = 1.0
  if (generateAbnormalData) {
    fev1ScaleFactor = 0.5 + Math.random() * 0.2
  }

  for (let i = 0; i < totalPoints; i++) {
    const t = i / mockFrequency.value
    let value

    if (t < peakTime) {
      const normalizedT = t / peakTime
      value = peakValue * Math.pow(normalizedT, riseSlope) /
          (Math.pow(normalizedT, riseSlope) + Math.pow(1-normalizedT, riseSlope))
    } else if (t < transitionTime) {
      value = peakValue * Math.exp(-(t - peakTime) / postPeakDecayFactor)
    } else {
      const valueAtTransition = peakValue * Math.exp(-(transitionTime - peakTime) / postPeakDecayFactor)
      value = valueAtTransition * Math.exp(-(t - transitionTime) / laterDecayFactor)
    }

    const noise = Math.sin(t * 8) * 0.1 + (Math.random() - 0.5) * 0.05
    value = Math.max(0, value + noise)

    if (t > 3 && value < 0.5) {
      value = Math.max(0.2, value)
    }

    if (generateAbnormalData && t <= 2) {
      value *= fev1ScaleFactor
    }

    mockSamplingData.value.push(value)
  }

  ensureNoRiseAfterPeak()
}

// 确保峰值后不会出现上升的情况
const ensureNoRiseAfterPeak = () => {
  let peakIndex = 0
  let peakValue = 0

  for (let i = 0; i < mockSamplingData.value.length; i++) {
    if (mockSamplingData.value[i] > peakValue) {
      peakValue = mockSamplingData.value[i]
      peakIndex = i
    }
  }

  for (let i = peakIndex + 1; i < mockSamplingData.value.length; i++) {
    if (mockSamplingData.value[i] > mockSamplingData.value[i-1]) {
      mockSamplingData.value[i] = mockSamplingData.value[i-1] * (0.98 + Math.random() * 0.01)
    }
  }
}

// 计算指标和图表数据
const calculateMetricsAndChartData = () => {
  fev1.value = 0
  fvc.value = 0
  chartData.value = []

  const samplingData = useMockData.value ? mockSamplingData.value : props.samplingData
  const frequency = useMockData.value ? mockFrequency.value : props.frequency

  samplingData.forEach((volume, index) => {
    const t = index / frequency

    if (t <= 1.5) {
      fev1.value += parseFloat(volume) * (1 / frequency)
    }
    fvc.value += parseFloat(volume) * (1 / frequency)

    chartData.value.push([t.toFixed(2), volume])
  })

  totalTime.value = Math.ceil(samplingData.length / frequency)
  maxFlowRate.value = Math.max(...samplingData.map(val => parseFloat(val)))
}


// 图表自适应
const resizeChart = () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
}

//图表自适应
const disposeChart = ()=>{
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  // 移除事件监听器
  // window.removeEventListener('resize', resizeCharts);
}

const editMode = ref(false)
const showEditInput = () => {
  editMode.value = !editMode.value;
};
const currentUserHeartRateData = ref({
  proportionList:{},
  evaluation:'在整夜睡眠中,入睡后心率波动在47.1-68.1次/分。可能存在心动过缓。'
});
const currentUserOxygenRateData = ref({
  proportionList:{}
});
</script>
<style scoped>

.blood-oxygen-container {
  width: 95%;
  padding: 20px;
  border-radius: 16px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;


}

/* 背景颜色和字体颜色根据血氧水平动态变化 */
.normal {
  background-color: #e6fffb;
}

.normal .oxygen-value,
.normal .status-text {
  color: #52c41a;
}

.low {
  background-color: #fff7e6;
}

.low .oxygen-value,
.low .status-text {
  color: #faad14;
}

.very-low {
  background-color: #fff1f0;
}

.very-low .oxygen-value,
.very-low .status-text {
  color: #f5222d;
}

.oxygen-display {
  display: flex;
  align-items: baseline;
  justify-content: center;
}

.oxygen-value {
  font-size:50px;
  font-weight: bold;
  margin-right: 10px;
}

.oxygen-label {
  font-size: 28px;
  color: #666666;
}

.oxygen-status {
  margin-top: 10px;
  text-align: center;
}

.status-text {
  font-size: 24px;
  font-weight: bold;
}

/* 新增过渡线条样式 */
.divider {
  width: 80%;
  height: 2px;
  background-color: #d9d9d9;
  margin: 20px 0;
}

.reference-range {
  width: 100%;
}

.range-title {
  margin-bottom: 10px;
  align-items: center;
  justify-content: center;
  display: flex;
}

.title-text {
  font-size: 24px;
  font-weight: bold;
  color: #333333;
}

.range-bar {
  display: flex;
  width: 100%;
  height: 60px;
  border-radius: 40px;
  overflow: hidden;
}

.range-segment {
  flex: 1;
  justify-content: center;
  align-items: center;
  display: flex;
}

.segment-text {
  font-size: 20px;
  color: #ffffff;
  text-align: center;
  white-space: pre-line;
}

.normal-segment {
  background-color: #52c41a;
}

.low-segment {
  background-color: #faad14;
}

.very-low-segment {
  background-color: #f5222d;
}

.main-container {
  width: 90%;
  height: 100%;
  background-color: #EFF2F9;
  border-radius: 20px;
}
.content-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title-container {
  width: 100%;
  height: 5%;
  margin-top: 2%;
}
.title-text {
  font-size: 18px;
  height: 100%;
  margin-left: 20px;
  align-items: center;
  display: flex;
}
.heartRateAnalysisCard {
  width: 100%;
  height: 10%;
  margin-top: 2%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.heartRateAnalysis {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;
  justify-content: center;
}
.analysisBegin {
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20px 0 0 20px;
  background-color: white;
}
.analysisCenter {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background-color: white;
}
.analysisEnd {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background-color: white;
  border-radius: 0 20px 20px 0;
}
.analysisCenterItem {
  display: flex;
  justify-content: center;
  align-items: center;
}
.icon-low {
  color: #FFDE00;
}
.icon-normal {
  color: #FE5997;
}
.icon-high {
  color: #FC8F42;
}
.rateGraphHeader {
  display: flex;
  margin-top: 10px;
  justify-content: center;
  align-items: center;
  width: 100%;
}
.rateGraphTitle {
  margin-right: auto;
  margin-left: 20px;
}
.chart-wrapper {
  width: 100%;
  height: 25%;
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}
/*.oxygen-chart-wrapper {*/
/*  min-height: 30%; !* 单独调整血氧时分图的高度 *!*/
/*}*/
.oxygen-chart-wrapper {
  width: 100%;
  min-height: 30%; /*!* 单独调整血氧时分图的高度 *!*!*/
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-container {
  width: 95%;
  height: 100%;
  border-radius: 20px;
  background-color: white;
  display: flex;
  flex-direction: column; /* 垂直排列 */
  align-items: center; /* 水平居中 */
  justify-content: space-between; /* 上下分布 */
  /*padding: 10px; !* 内边距 *!*/
}

.chart {
  border-radius: 20px;
  width: 95%;
  height: 100%;
}
.evaluation-wrapper {
  width: 100%;
  height: 15%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}
.evaluation-content {
  width: 95%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.evaluation-header {
  width: 100%;
  height: 30%;
  display: flex;
}
.icon {
  height: 100%;
}
.icon-color {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
}
.evaluation-title {
  font-size: 17px;
  font-weight: 510;
}
.edit-button {
  height: 100%;
  margin-left: auto;
  background-color: #EFF2F9;
  border: none;
}
.edit-icon {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
  width: 20px;
  height: 20px;
}
.edit-text {
  font-size: 17px;
  color: #3DD986;
}
.evaluation-body {
  width: 100%;
  height: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.evaluation-input {
  height: 100%;
  width: 95%;
}
.evaluation-display {
  width: 90%;
  font-size: 15px;
  margin-left: 30px;
  margin-top: 10px;
}

.stats-container {
  width: 93%;
  height: 20%; /* 统计数据占 20% 高度 */
  display: flex;
  flex-direction: row; /* 水平排列 */
  justify-content: space-around; /* 均匀分布 */
  align-items: center; /* 垂直居中 */
  background-color: white;
  border-radius: 20px;
  padding: 10px;
  gap: 20px;
  /*margin-top: 10px; !* 与血氧时分图的间距 *!*/
}

.stat-item {
  width: 25%; /* 每个统计项均匀分布 */
  text-align: center; /* 文字居中 */
  padding: 10px; /* 内边距 */
  margin: 0 5px; /* 左右间距 */
  border-radius: 10px;
  display: flex;
  flex-direction: column; /* 垂直排列 */
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中 */
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
}
/* 最低血氧盒子（第一个子元素） */
.stat-item:first-child {
  background-color: #fff4e6;
  border: 1px solid #ff9500; /* 深橙色边框 */
}
/* 最高血氧盒子（第二个子元素） */
.stat-item:nth-child(2) {
  background-color: #e6ffed;
  border: 1px solid #34c759;
}
/* 平均血氧盒子（最后一个子元素） */
.stat-item:last-child {
  background-color: #fff4e6; /* 浅橙色背景 */
  border: 1px solid #ff9500; /* 深橙色边框 */
}
.min-oxygen-value {
  color: #ff9500; /* 文本颜色为橙色 */
}
.max-oxygen-value {
  color: #34c759; /* 文本颜色为橙色 */
}
.avg-oxygen-value{
  color: #ff9500; /* 文本颜色为橙色 */
}


.stat-title {
  font-size: 14px;
  font-weight: bold;
  color: #666;
}



/* 血氧状态样式 */
.stat-good {
  background-color: #e6f7e6; /* 正常状态背景色 */
  color: #52c41a; /* 正常状态文字颜色 */
}

.stat-warning {
  background-color: #fffbe6; /* 警告状态背景色 */
  color: #faad14; /* 警告状态文字颜色 */
}

.stat-danger {
  background-color: #ffe6e6; /* 危险状态背景色 */
  color: #ff4d4f; /* 危险状态文字颜色 */
}


</style>